<template>
	<el-container class="home-container">
		<!-- 侧边导航栏 -->
		<el-aside width="80px" class="side-nav" v-if="$route.path != rurl">
			<!-- 用户头像区域 -->
			<div class="user-profile">
				<el-avatar
					:size="50"
					class="user-avatar"
					@click="showSetting"
					:src="$store.state.userStore.userInfo.headImage">
					<span>{{ $store.state.userStore.userInfo.nickName?.charAt(0) }}</span>
				</el-avatar>
			</div>

			<!-- 主导航菜单 -->
			<div class="nav-container">
				<!-- 聊天菜单项 -->
				<div class="nav-item" :class="{ active: activeMenu === '/home/chat' }">
					<el-tooltip
						effect="dark"
						content="聊天"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<router-link to="/home/chat" class="nav-button">
							<el-badge :value="unreadCount" :hidden="unreadCount <= 0" class="unread-badge">
								<el-icon><ChatDotRound /></el-icon>
							</el-badge>
						</router-link>
					</el-tooltip>
				</div>

				<!-- 好友菜单项 -->
				<div class="nav-item" :class="{ active: activeMenu === '/home/friend' }">
					<el-tooltip
						effect="dark"
						content="好友"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<router-link to="/home/friend" class="nav-button">
							<el-badge :value="$store.state.friendStore.friendApplyCount" :hidden="$store.state.friendStore.friendApplyCount === 0" class="apply-badge">
								<el-icon><UserFilled /></el-icon>
							</el-badge>
						</router-link>
					</el-tooltip>
				</div>

				<!-- 群聊菜单项 -->
				<div class="nav-item" :class="{ active: activeMenu === '/home/group' }">
					<el-tooltip
						effect="dark"
						content="群聊"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<router-link to="/home/group" class="nav-button">
							<el-icon><Service /></el-icon>
						</router-link>
					</el-tooltip>
				</div>

				<!-- 示例菜单 - 下拉菜单形式 -->
				<div class="nav-item" style="display: none;">
					<el-dropdown trigger="click" @command="handleModuleNavigation">
						<div class="nav-button">
							<el-icon><Menu /></el-icon>
						</div>
						<template #dropdown>
							<el-dropdown-menu>
								<!-- Cross 模块 -->
								<el-dropdown-item command="showCrossMenu">
									<div class="module-item">
										<el-icon><Connection /></el-icon>
										<span>跨语言调用</span>
										<el-icon class="expand-icon"><ArrowRight /></el-icon>
									</div>
								</el-dropdown-item>

								<!-- Effect 模块 -->
								<el-dropdown-item command="showEffectMenu">
									<div class="module-item">
										<el-icon><PictureFilled /></el-icon>
										<span>特效示例</span>
										<el-icon class="expand-icon"><ArrowRight /></el-icon>
									</div>
								</el-dropdown-item>

								<!-- Framework 模块 -->
								<el-dropdown-item command="showFrameworkMenu">
									<div class="module-item">
										<el-icon><Grid /></el-icon>
										<span>框架功能</span>
										<el-icon class="expand-icon"><ArrowRight /></el-icon>
									</div>
								</el-dropdown-item>

								<!-- OS 模块 -->
								<el-dropdown-item command="showOsMenu">
									<div class="module-item">
										<el-icon><Monitor /></el-icon>
										<span>系统功能</span>
										<el-icon class="expand-icon"><ArrowRight /></el-icon>
									</div>
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>

				<!-- 设置菜单项 -->
				<div class="nav-item">
					<el-tooltip
						effect="dark"
						content="设置"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button" @click="showSetting()">
							<el-icon><Setting /></el-icon>
						</div>
					</el-tooltip>
				</div>
			</div>

			<!-- 底部工具栏 -->
			<div class="bottom-tools">
				<!-- 刷新按钮 -->
				<div class="tool-item">
					<el-tooltip
						effect="dark"
						content="刷新页面"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button" @click="refreshWin">
							<el-icon><Refresh /></el-icon>
						</div>
					</el-tooltip>
				</div>

				<!-- 主题设置 -->
				<div class="tool-item">
					<el-dropdown trigger="click" @command="handleThemeChange">
						<div class="nav-button">
							<el-icon><Brush /></el-icon>
						</div>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item
									v-for="(color, name) in themeColors"
									:key="name"
									:command="color">
									<div class="theme-item">
										<div class="color-block" :style="{ backgroundColor: color }"></div>
										<span>{{ name }}</span>
									</div>
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>

				<!-- 移动端链接 -->
				<div class="tool-item">
					<el-tooltip
						effect="dark"
						content="移动端"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button" @click="openMobileLink">
							<el-icon><Iphone /></el-icon>
						</div>
					</el-tooltip>
				</div>

				<!-- 关于我们 -->
				<div class="tool-item">
					<el-tooltip
						effect="dark"
						content="关于我们"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button" @click="aboutMy">
							<el-icon><InfoFilled /></el-icon>
						</div>
					</el-tooltip>
				</div>

				<!-- 检查更新 -->
				<div class="tool-item">
					<el-tooltip
						effect="dark"
						content="检查更新"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button" @click="checkForUpdate">
							<el-icon><Download /></el-icon>
						</div>
					</el-tooltip>
				</div>

				<!-- 退出按钮 -->
				<div class="tool-item">
					<el-tooltip
						effect="dark"
						content="退出"
						placement="right"
						:enterable="false"
						trigger="hover"
					>
						<div class="nav-button danger" @click="onExit">
							<el-icon><SwitchButton /></el-icon>
						</div>
					</el-tooltip>
				</div>
			</div>
		</el-aside>

		<!-- 主内容区域 -->
		<el-container class="main-content">
			<el-main>
				<router-view></router-view>
			</el-main>
		</el-container>

		<!-- 弹窗组件 -->
		<settings v-model:visible="showSettingDialog" @close="closeSetting()"></settings>
		<user-info
			v-show="$store.state.uiStore.userInfo.visible && uiStore.userInfo.user"
			:user="uiStore.userInfo.user || {}"
			@close="$store.commit('hideUserInfoBox')">
		</user-info>
		<full-image
			:visible="uiStore.fullImage.show"
			:url="uiStore.fullImage.url"
			@close="$store.commit('closeFullImageBox')">
		</full-image>
		<rtc-private-video ref="rtcPrivateVideo"></rtc-private-video>
		<rtc-group-video ref="rtcGroupVideo"></rtc-group-video>
		<AboutUs
			v-model:visible="showAboutUsDialog"
			:companyName="companyInfo.name"
			:companyDescription="companyInfo.description"
			:qrCodeImageUrl="companyInfo.qrCodeUrl"
			:copyrightYear="companyInfo.copyright">
		</AboutUs>

		<!-- 模块子菜单 - Cross -->
		<el-dialog
			v-model="showCrossMenuDialog"
			title="跨语言调用示例"
			width="300px"
			:append-to-body="true">
			<div class="module-menu-grid">
				<router-link to="/home/cross/python" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Platform /></el-icon>
						<span>Python</span>
					</div>
				</router-link>
				<router-link to="/home/cross/java" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Coffee /></el-icon>
						<span>Java</span>
					</div>
				</router-link>
				<router-link to="/home/cross/go" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Promotion /></el-icon>
						<span>Go</span>
					</div>
				</router-link>
			</div>
		</el-dialog>

		<!-- 模块子菜单 - Effect -->
		<el-dialog
			v-model="showEffectMenuDialog"
			title="特效示例"
			width="300px"
			:append-to-body="true">
			<div class="module-menu-grid">
				<router-link to="/home/effect/login" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Key /></el-icon>
						<span>登录效果</span>
					</div>
				</router-link>
				<router-link to="/home/effect/login/window" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><SwitchButton /></el-icon>
						<span>窗口切换</span>
					</div>
				</router-link>
			</div>
		</el-dialog>

		<!-- 模块子菜单 - Framework -->
		<el-dialog
			v-model="showFrameworkMenuDialog"
			title="框架功能"
			width="500px"
			:append-to-body="true">
			<div class="module-menu-grid">
				<router-link to="/home/framework/updater" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Upload /></el-icon>
						<span>更新器</span>
					</div>
				</router-link>
				<router-link to="/home/framework/sqlitedb" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><DataBoard /></el-icon>
						<span>数据库</span>
					</div>
				</router-link>
				<router-link to="/home/framework/software" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Box /></el-icon>
						<span>系统信息</span>
					</div>
				</router-link>
				<router-link to="/home/framework/jobs" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Timer /></el-icon>
						<span>定时任务</span>
					</div>
				</router-link>
				<router-link to="/home/framework/socket/http-server" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><List /></el-icon>
						<span>HTTP服务</span>
					</div>
				</router-link>
				<router-link to="/home/framework/socket/socket-server" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Link /></el-icon>
						<span>Socket服务</span>
					</div>
				</router-link>
				<router-link to="/home/framework/socket/ipc" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Operation /></el-icon>
						<span>IPC通信</span>
					</div>
				</router-link>
			</div>
		</el-dialog>

		<!-- 模块子菜单 - OS -->
		<el-dialog
			v-model="showOsMenuDialog"
			title="系统功能"
			width="400px"
			:append-to-body="true">
			<div class="module-menu-grid">
				<router-link to="/home/os/window" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><FullScreen /></el-icon>
						<span>窗口管理</span>
					</div>
				</router-link>
				<router-link to="/home/os/subwindow/ipc" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><CopyDocument /></el-icon>
						<span>子窗口通信</span>
					</div>
				</router-link>
				<router-link to="/home/os/notification" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Bell /></el-icon>
						<span>通知</span>
					</div>
				</router-link>
				<router-link to="/home/os/file" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Folder /></el-icon>
						<span>文件操作</span>
					</div>
				</router-link>
				<router-link to="/home/os/file/pic" custom v-slot="{ navigate }">
					<div class="module-grid-item" @click="navigate">
						<el-icon><Picture /></el-icon>
						<span>图片查看</span>
					</div>
				</router-link>
			</div>
		</el-dialog>

		<!-- 更新对话框 -->
		<el-dialog
			v-model="showUpdateDialog"
			title="更新"
			width="300px"
			:append-to-body="true">
			<div class="update-content">
				<p>版本: {{ updateInfo.version }}</p>
				<p>更新说明: {{ updateInfo.releaseNotes }}</p>
				<el-progress
					:percentage="downloadProgress"
					:format="progressFormat"
					:stroke-width="20"
					status="active">
				</el-progress>
				<p>进度: {{ progressInfo }}</p>
			</div>
			<template #footer>
				<el-button @click="doUpdate">开始更新</el-button>
			</template>
		</el-dialog>
	</el-container>
</template>

<script>
	import HeadImage from '../components/common/HeadImage.vue';
	import Settings from '../components/setting/Setting.vue';
	import AboutUs from '../components/setting/AboutUs.vue';
	import UserInfo from '../components/common/UserInfo.vue';
	import FullImage from '../components/common/FullImage.vue';
	import RtcPrivateVideo from '../components/rtc/RtcPrivateVideo.vue';
	import RtcPrivateAcceptor from '../components/rtc/RtcPrivateAcceptor.vue';
	import RtcGroupVideo from '../components/rtc/RtcGroupVideo.vue';
	import {getAccessToken,removeToken} from '@/utils/auth'
	import emitter from '@/utils/eventBus';
	import { ipcApiRoute, specialIpcRoute } from '@/api';
	import { ipc } from '@/utils/ipcRenderer';
	import { useRoute } from 'vue-router';
	import { computed, ref, onMounted, onUnmounted } from 'vue';
	import {
		ChatDotRound, UserFilled, Service, Setting, Refresh, Brush,
		Iphone, InfoFilled, SwitchButton, Menu, Connection, PictureFilled,
		Grid, Monitor, ArrowRight, Platform, Coffee, Promotion, Key,
		DataBoard, Box, Timer, List, Link, Operation, FullScreen,
		CopyDocument, Bell, Folder, Picture, Upload, Download
	} from '@element-plus/icons-vue';
	import { ElMessage } from 'element-plus';

	export default {
		name: 'Home',
		components: {
			HeadImage,
			Settings,
			AboutUs,
			UserInfo,
			FullImage,
			RtcPrivateVideo,
			RtcPrivateAcceptor,
			RtcGroupVideo,
			ChatDotRound,
			UserFilled,
			Service,
			Setting,
			Refresh,
			Brush,
			Iphone,
			InfoFilled,
			SwitchButton,
			Menu,
			Connection,
			PictureFilled,
			Grid,
			Monitor,
			ArrowRight,
			Platform,
			Coffee,
			Promotion,
			Key,
			DataBoard,
			Box,
			Timer,
			List,
			Link,
			Operation,
			FullScreen,
			CopyDocument,
			Bell,
			Folder,
			Picture,
			Upload,
			Download
		},
		setup() {
			const route = useRoute();
			const activeMenu = computed(() => route.path);

			return {
				activeMenu
			};
		},
		data() {
			return {
				companyInfo:{
					name:'会泽县拓创科技有限公司',
					description:'会泽县拓创科技有限公司成立于2023年，是一家集研发、生产、销售为一体的高新技术企业，公司致力于为广大客户提供优质的产品和服务。公司拥有一支高素质的技术团队，具备丰富的研发经验和技能力，能够为客户提供高质量的产品和服务公司注重产品的质量和性能，不断创新和改进产品，以满足客户的需求。',
					qrCodeUrl: new URL('@/assets/image/me.jpg', import.meta.url).href,
					copyright:'2024',
				},
				rurl:'',
				showAboutUsDialog: false,
				showSettingDialog: false,
				lastPlayAudioTime: new Date().getTime() - 1000,
				themeColors: {
					'默认蓝': '#409EFF',
					'清新绿': '#67C23A',
					'活力橙': '#E6A23C',
					'温暖红': '#F56C6C',
					'沉稳紫': '#9B59B6',
					'天空蓝': '#1E90FF',
					'柠檬黄': '#FFD700',
					'樱花粉': '#FFB6C1'
				},
				tipAudioUrl: new URL('@/assets/audio/tip.wav', import.meta.url).href,
				selectedColor: '#409EFF',
				showCrossMenuDialog: false,
				showEffectMenuDialog: false,
				showFrameworkMenuDialog: false,
				showOsMenuDialog: false,
				// 更新相关状态
				updating: false,
				checking: false,
				downloadProgress: 0,
				progressInfo: '',
				showUpdateDialog: false,
				updateInfo: {
					version: '',
					releaseNotes: ''
				},
			}
		},
		created() {
			// 初始化IPC引用，确保可以使用this.$ipc
			const isElectron = window.electron || (window.require && window.require('electron'));
			if (isElectron) {
				this.$ipc = ipc;
			}
		},
		methods: {
			refreshWin(){
				window.location.reload();
			},
			aboutMy(){
				this.showAboutUsDialog = true;
			},
			init() {
				emitter.on('openPrivateVideo', (rctInfo) => {
					// 进入单人视频通话
					this.$refs.rtcPrivateVideo.open(rctInfo);
				});

				emitter.on('openGroupVideo', (rctInfo) => {
					// 进入多人视频通话
					this.$refs.rtcGroupVideo.open(rctInfo);
				});

				this.$store.dispatch("load").then(() => {
					// ws初始化
					this.$wsApi.connect(import.meta.env.VITE_WS_URL,getAccessToken());
					this.$wsApi.onConnect(() => {
						// 加载离线消息
						this.pullPrivateOfflineMessage(this.$store.state.chatStore.privateMsgMaxId);
						this.pullGroupOfflineMessage(this.$store.state.chatStore.groupMsgMaxId);
					});
					this.$wsApi.onMessage((cmd, msgInfo) => {
						if (cmd == 2) {
							// 关闭ws
							this.$wsApi.close(3000)
							// 异地登录，强制下线
							this.$alert("您已在其他地方登陆，将被强制下线", "强制下线通知", {
								confirmButtonText: '确定',
								callback: action => {
									if (process.env.NODE_ENV=="development") {
										location.href = "/";
									}else{
										location.href ='app://./index.html';
									}
								}
							});

						} else if (cmd == 3) {
							// 插入私聊消息
							this.handlePrivateMessage(msgInfo);
						} else if (cmd == 4) {
							// 插入群聊消息
							this.handleGroupMessage(msgInfo);
						} else if (cmd == 5){
							// 处理系统消息
							this.handleSystemMessage(msgInfo);
						}
					});
					this.$wsApi.onClose((e) => {
						console.log(e);
						if (e.code != 3000) {
							// 断重连
							this.$message.error("连接断开，正在尝试重新连接...");
							this.$wsApi.reconnect(import.meta.env.VITE_WS_URL, getAccessToken());
						}
					});
				}).catch((e) => {
					console.log("初始化失败", e);
				})
			},
			pullPrivateOfflineMessage(minId) {
				this.$store.commit("loadingPrivateMsg", true)
				this.$http({
					url: "/message/private/pullOfflineMessage?minId=" + minId,
					method: 'GET'
				}).catch(() => {
					this.$store.commit("loadingPrivateMsg", false)
				})
			},
			pullGroupOfflineMessage(minId) {
				this.$store.commit("loadingGroupMsg", true)
				this.$http({
					url: "/message/group/pullOfflineMessage?minId=" + minId,
					method: 'GET'
				}).catch(() => {
					this.$store.commit("loadingGroupMsg", false)
				})
			},
			handlePrivateMessage(msg) {
				// 消息加载标志
				if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
					this.$store.commit("loadingPrivateMsg", JSON.parse(msg.content))
					return;
				}
				// 消息已读处理，清空已读数量
				if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
					this.$store.commit("resetUnreadCount", {
						type: 'PRIVATE',
						targetId: msg.recvId
					})
					return;
				}
				// 消息回执处理,改消息状态为已读
				if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
					this.$store.commit("readedMessage", {
						friendId: msg.sendId
					})
					return;
				}
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
				// 单人webrtc 信令
				if (this.$msgType.isRtcPrivate(msg.type)) {
					this.$refs.rtcPrivateVideo.onRTCMessage(msg)
					return;
				}
				// 好友id
				let friendId = msg.selfSend ? msg.recvId : msg.sendId;
				this.loadFriendInfo(friendId).then((friend) => {
					this.insertPrivateMessage(friend, msg);
				})
			},
			insertPrivateMessage(friend, msg) {
				let chatInfo = {
					type: 'PRIVATE',
					targetId: friend.id,
					showName: friend.nickName,
					headImage: friend.headImage
				};
				if(msg.privateMessage){
					msg.privateMessage=JSON.parse(msg.privateMessage);
					chatInfo.privateMessage=msg.privateMessage;
				}
				// 打开会话
				this.$store.commit("openChat", chatInfo);
				// 插入消息
				this.$store.commit("insertMessage", msg);
				this.$forceUpdate();
				// 播放提示音
				if (!msg.selfSend && this.$msgType.isNormal(msg.type) &&
					msg.status != this.$enums.MESSAGE_STATUS.READED) {
					this.playAudioTip();
				}
			},
			handleGroupMessage(msg) {
				// 消息加载标志
				if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
					this.$store.commit("loadingGroupMsg", JSON.parse(msg.content))
					return;
				}
				// 消息已读处理
				if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
					// 我已读对方的消息，清空已读数量
					let chatInfo = {
						type: 'GROUP',
						targetId: msg.groupId
					}
					this.$store.commit("resetUnreadCount", chatInfo)
					return;
				}
				// 消息回执处理
				if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
					// 更新消息已读人数
					let msgInfo = {
						id: msg.id,
						groupId: msg.groupId,
						readedCount: msg.readedCount,
						receiptOk: msg.receiptOk
					};
					this.$store.commit("updateMessage", msgInfo)
					return;
				}
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
				// 群视频信令
				if (this.$msgType.isRtcGroup(msg.type)) {
					this.$nextTick(() => {
						this.$refs.rtcGroupVideo.onRTCMessage(msg);
					})
					return;
				}
				this.loadGroupInfo(msg.groupId).then((group) => {
					// 插入群聊消息
					this.insertGroupMessage(group, msg);
				})
			},
			insertGroupMessage(group, msg) {
				let chatInfo = {
					type: 'GROUP',
					targetId: group.id,
					showName: group.showGroupName,
					headImage: group.headImage
				};
				if(msg.privateMessage){
					msg.privateMessage=JSON.parse(msg.privateMessage);
					chatInfo.privateMessage = msg.privateMessage;
				}
				// 打开会话
				this.$store.commit("openChat", chatInfo);
				// 插入消息
				this.$store.commit("insertMessage", msg);
				// 播放提示音
				if (!msg.selfSend && msg.type <= this.$enums.MESSAGE_TYPE.VIDEO &&
					msg.status != this.$enums.MESSAGE_STATUS.READED) {
					this.playAudioTip();
				}
			},
			handleSystemMessage(msg){
				// 用户被封禁
				if (msg.type == this.$enums.MESSAGE_TYPE.USER_BANNED) {
					this.$wsApi.close(3000);
					this.$alert("您的账号已被管理员封禁,原因:"+ msg.content, "账号被封禁", {
						confirmButtonText: '确定',
						callback: action => {
							this.onExit();
						}
					});
					return;
				}
				// 好友申请
				if(msg.type == this.$enums.MESSAGE_TYPE.FRIEND_APPLY){
					this.$store.commit('friendApplyMessage',msg);
					this.$store.commit('incrementFriendApplyCount');
					this.$notify({
						title: '新的好友申请',
						message: `${msg.sendNickName}请求添加您为好友`,
						type: 'info'
					});
					return;
				}
				//好友申请通过
				if(msg.type == this.$enums.MESSAGE_TYPE.FRIEND_APPLY_PASS){
					this.$notify({
						title: '好友申请通过',
						message: `${msg.sendNickName}同意了您的申请`,
						type: 'success'
					});
					return;
				}
			},
			onExit() {
				this.$confirm('您确定要退出系统吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 先清理聊天状态
					this.$store.commit("clear");
					// 关闭websocket连接
					this.$wsApi.close(3000);
					// 清除token
					removeToken();
					sessionStorage.removeItem("accessToken");
					// 跳转到登录页
					this.$router.push('/');
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				});
			},
			playAudioTip() {
				// 离线消息不播放铃声
				if(this.$store.getters.isLoading()){
					return;
				}
				// 防止过于密集播放
				if (new Date().getTime() - this.lastPlayAudioTime > 1000) {
					this.lastPlayAudioTime = new Date().getTime();
					let audio = new Audio();
					audio.src = this.tipAudioUrl;
					audio.play();
				}
			},
			showSetting() {
				this.showSettingDialog = true;
			},
			closeSetting() {
				this.showSettingDialog = false;
			},
			loadFriendInfo(id) {
				return new Promise((resolve, reject) => {
					let friend = this.$store.state.friendStore.friends.find((f) => f.id == id);
					if (friend) {
						resolve(friend);
					} else {
						this.$http({
							url: `/friend/find/${id}`,
							method: 'get'
						}).then((friend) => {
							this.$store.commit("addFriend", friend);
							resolve(friend)
						})
					}
				});
			},
			loadGroupInfo(id) {
				return new Promise((resolve, reject) => {
					let group = this.$store.state.groupStore.groups.find((g) => g.id == id);
					if (group) {
						resolve(group);
					} else {
						this.$http({
							url: `/group/find/${id}`,
							method: 'get'
						}).then((group) => {
							group.id=id;
							resolve(group)
							console.log(group);
							this.$store.commit("addGroup", group);
						})
					}
				});
			},
			handleThemeChange(color) {
				this.selectedColor = color;
				this.$store.commit('setThemeColor', color);
				this.updateThemeColor(color);
			},
			updateThemeColor(color) {
				document.documentElement.style.setProperty('--el-color-primary', color);

				// 生成不同透明度的主题色
				const rgb = this.hexToRgb(color);
				for(let i = 1; i <= 9; i++) {
					document.documentElement.style.setProperty(
						`--el-color-primary-light-${i}`,
						`rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${1 - i * 0.1})`
					);
				}
				document.documentElement.style.setProperty(
					'--el-color-primary-dark-2',
					this.darkenColor(color, 0.2)
				);
			},
			hexToRgb(hex) {
				let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
				return result ? {
					r: parseInt(result[1], 16),
					g: parseInt(result[2], 16),
					b: parseInt(result[3], 16)
				} : null;
			},
			darkenColor(hex, amount) {
				let rgb = this.hexToRgb(hex);
				return `#${Math.round(rgb.r * (1 - amount)).toString(16).padStart(2, '0')}${
					Math.round(rgb.g * (1 - amount)).toString(16).padStart(2, '0')}${
					Math.round(rgb.b * (1 - amount)).toString(16).padStart(2, '0')}`;
			},
			showUserInfo(event) {
				// 获取当前用户信息
				const userInfo = this.$store.state.userStore.userInfo;

				// 显示用户信息弹窗
				this.$store.commit('showUserInfoBox', {
					id: userInfo.id,
					userId: userInfo.id,
					headImage: userInfo.headImage,
					nickName: userInfo.nickName,
					userName: userInfo.userName,
					sex: userInfo.sex,
					signature: userInfo.signature
				});
			},
			handleModuleNavigation(command) {
				switch(command) {
					case 'showCrossMenu':
						this.showCrossMenuDialog = true;
						break;
					case 'showEffectMenu':
						this.showEffectMenuDialog = true;
						break;
					case 'showFrameworkMenu':
						this.showFrameworkMenuDialog = true;
						break;
					case 'showOsMenu':
						this.showOsMenuDialog = true;
						break;
				}
			},
			openMobileLink() {
				// 检查是否在Electron环境中
				const isElectron = window.electron || (window.require && window.require('electron'));

				if (isElectron) {
					try {
						// 使用electron-egg框架的窗口创建API
						const mobileViewConfig = {
							type: 'web',
							content: 'https://yn-zgq.top/web/index.html',
							windowName: 'window-mobile',
							windowTitle: '拓聊移动端'
						};

						this.$ipc.invoke(ipcApiRoute.os.createWindow, mobileViewConfig)
							.then(winId => {
								console.log('移动端窗口创建成功，ID:', winId);
							})
							.catch(err => {
								console.error('移动端窗口创建失败:', err);
								// 创建失败时降级为浏览器打开
								window.open('https://yn-zgq.top/web/index.html', '_blank');
							});
					} catch (error) {
						console.error('创建窗口过程中出错:', error);
						// 发生错误时降级为浏览器打开
						window.open('https://yn-zgq.top/web/index.html', '_blank');
					}
				} else {
					// 非Electron环境直接使用浏览器打开
					window.open('https://yn-zgq.top/web/index.html', '_blank');
				}
			},
			checkForUpdate() {
				this.checking = true;
				ElMessage.info('正在检查更新...');
				console.log('开始请求更新检查...');
				
				ipc.invoke(ipcApiRoute.framework.checkForUpdater)
					.then(res => {
						console.log('检查更新结果:', res);
						
						if (res) {
							if (res.success && res.data) {
								console.log('更新检查成功，结果数据:', res.data);
								// 显示URL信息，帮助调试
								if (res.data.url) {
									console.log('更新服务器URL:', res.data.url);
								}
								// 更新检查成功，由事件监听器处理后续操作
							} else {
								// 返回了结果但没有预期的数据结构
								console.warn('检查更新失败，原因:', res.message);
								ElMessage.warning(res.message || '检查更新结果格式异常，请稍后再试');
								
								// 显示额外调试信息
								if (res.message && res.message.includes('超时')) {
									console.error('请求超时，请检查更新服务器是否可访问，或网络是否正常');
									ElMessage.error('请求超时，请确认更新服务器是否正确配置并可访问');
								}
							}
						} else {
							console.warn('检查更新返回空结果');
							ElMessage.info('检查更新返回空结果，可能是因为更新服务未正确配置');
						}
						// 无论如何，都在一段时间后重置checking状态
						setTimeout(() => {
							this.checking = false;
						}, 3000);
					})
					.catch(err => {
						this.checking = false;
						console.error('检查更新失败:', err);
						ElMessage.error('检查更新失败: ' + (err.message || String(err)));
					});
			},
			doUpdate() {
				this.showUpdateDialog = false;
				this.updating = true;
				this.progressInfo = '准备下载更新...';
				
				ElMessage.info('正在开始下载更新...');
				
				ipc.invoke(ipcApiRoute.framework.downloadApp)
					.then(res => {
						console.log('开始下载更新结果:', res);
						
						if (res) {
							if (res.success) {
								ElMessage.success('开始下载更新');
							} else {
								// 响应不符合预期
								ElMessage.warning('开始下载时返回失败状态，请稍后再试');
								// 失败后重置状态
								setTimeout(() => {
									this.updating = false;
								}, 3000);
							}
						} else {
							ElMessage.info('下载请求返回空结果，可能是因为下载服务未正确配置');
							// 失败后重置状态
							setTimeout(() => {
								this.updating = false;
							}, 3000);
						}
						// 下载进度由事件监听器处理
					})
					.catch(err => {
						this.updating = false;
						console.error('下载更新失败:', err);
						ElMessage.error('下载更新失败: ' + (err.message || String(err)));
					});
			},
			progressFormat(percentage) {
				return percentage === 100 ? '下载完成' : `${percentage}%`;
			},
			initUpdaterListener() {
				// 移除所有之前的监听器，避免重复监听
				ipc.removeAllListeners(specialIpcRoute.appUpdater);
				
				// 添加更新事件监听
				ipc.on(specialIpcRoute.appUpdater, (event, result) => {
					try {
						const res = JSON.parse(result);
						console.log('更新服务响应:', res);
						
						// 如果有URL信息，打印出来
						if (res.url) {
							console.log('更新服务器地址:', res.url);
						}
						
						switch(res.status) {
							case -1: // 错误
								this.checking = false;
								this.updating = false;
								ElMessage.error(res.desc || '检查更新失败');
								console.error('更新错误详情:', res.error || '无详细信息');
								break;
							case 0: // 开始检查
								console.log('开始检查更新，使用URL:', res.url);
								this.checking = true;
								break;
							case 1: // 有可用更新
								this.checking = false;
								// 显示更新对话框
								this.updateInfo.version = res.version || '新版本';
								this.updateInfo.releaseNotes = res.releaseNotes || '';
								this.showUpdateDialog = true;
								break;
							case 2: // 没有可用更新
								this.checking = false;
								ElMessage.info(res.desc || '已经是最新版本');
								break;
							case 3: // 下载中
								this.updating = true;
								this.downloadProgress = res.percentNumber || 0;
								this.progressInfo = res.desc || '正在下载更新...';
								break;
							case 4: // 下载完成
								this.updating = true;
								this.downloadProgress = 100;
								this.progressInfo = '下载完成，准备安装...';
								ElMessage.success('更新下载完成，即将安装');
								break;
							default:
								console.log('未知状态码:', res.status);
						}
					} catch (error) {
						console.error('处理更新消息出错:', error);
					}
				});
			},
		},
		computed: {
			uiStore() {
				return this.$store.state.uiStore;
			},
			unreadCount() {
				let unreadCount = 0;
				let chats = this.$store.state.chatStore.chats;
				chats.forEach((chat) => {
					if(!chat.delete){
						// 确保unreadCount是数字，如果不是则视为0
						const count = chat.unreadCount;
						unreadCount += (typeof count === 'number' && !isNaN(count)) ? count : 0;
					}
				});
				return unreadCount;
			}
		},
		watch: {
			unreadCount: {
				handler(newCount) {
					document.title = newCount > 0 ? `(${newCount}条未读)拓聊` : "拓聊";
				},
				immediate: true
			},
			showAboutUsDialog: {
				handler(newVal) {
					console.log('Home.vue: showAboutUsDialog变化为:', newVal);
				}
			}
		},
		mounted() {
			this.init();
			if(this.$route.path.indexOf('/home/chatbox/')!=-1){
				this.rurl=this.$route.path
			}
			// 初始化主题色
			const savedColor = this.$store.state.themeColor || '#409EFF';
			this.updateThemeColor(savedColor);
			// 初始化更新监听器
			this.initUpdaterListener();
		},
		unmounted() {
			emitter.off('openPrivateVideo');
			emitter.off('openGroupVideo');
			this.$wsApi.close();
			// 组件销毁时移除监听器
			ipc.removeAllListeners(specialIpcRoute.appUpdater);
		}
	}
</script>

<style lang="scss" scoped>
.home-container {
	display: flex;
	height: 100vh;
	margin: 0;
	padding: 0;
	overflow: hidden;

	:deep(.el-container) {
		margin: 0;
		padding: 0;
		height: 100%;
	}

	:deep(.el-main) {
		margin: 0;
		padding: 0;
		height: 100%;
		overflow: hidden;
	}

	.side-nav {
		display: flex;
		flex-direction: column;
		background-color: #f0f5ff;
		border-right: 1px solid #e0e6f5;
		transition: all 0.3s;
		z-index: 1000;
		padding: 0;

		.user-profile {
			padding: 20px 0;
			display: flex;
			justify-content: center;
			border-bottom: 1px solid #e0e6f5;

			.user-avatar {
				cursor: pointer;
				transition: transform 0.3s;
				border: 2px solid transparent;

				&:hover {
					transform: scale(1.05);
					border-color: var(--el-color-primary);
				}
			}
		}

		.nav-container {
			flex: 1;
			display: flex;
			flex-direction: column;
			padding: 10px 0;

			.nav-item {
				height: 60px;
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 5px 0;
			}
		}

		.bottom-tools {
			padding: 15px 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			border-top: 1px solid #e0e6f5;
			background-color: #eef4fb;

			.tool-item {
				height: 45px;
				width: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.nav-button {
			height: 40px;
			width: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			color: #67727e;
			cursor: pointer;
			text-decoration: none;
			transition: all 0.2s;
			background-color: transparent;

			.el-icon {
				font-size: 22px;
			}

			&:hover {
				background-color: rgba(64, 158, 255, 0.1);
				color: var(--el-color-primary);

				.el-icon {
					transform: scale(1.1);
				}
			}

			&.danger:hover {
				background-color: rgba(245, 108, 108, 0.1);
				color: #F56C6C;
			}
		}

		.nav-item.active .nav-button {
			color: var(--el-color-primary);
			background-color: rgba(64, 158, 255, 0.1);
		}
	}

	.main-content {
		flex: 1;
		margin: 0;
		padding: 0;
		overflow: hidden;
		background-color: #fff;
		height: 100vh;
	}
}

.unread-badge {
	:deep(.el-badge__content) {
		z-index: 1;
		background-color: #ff6b6b;
	}
}

.theme-item {
	display: flex;
	align-items: center;
	padding: 8px;

	.color-block {
		width: 20px;
		height: 20px;
		border-radius: 4px;
		margin-right: 8px;
		border: 1px solid var(--el-border-color);
	}
}

.module-item {
	display: flex;
	align-items: center;
	gap: 8px;

	.expand-icon {
		margin-left: auto;
	}
}

.module-menu-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
	gap: 15px;
	padding: 10px;

	.module-grid-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #f5f7fa;
		border-radius: 8px;
		padding: 15px 10px;
		cursor: pointer;
		transition: all 0.3s ease;

		&:hover {
			background: var(--el-color-primary-light-8);
			transform: translateY(-3px);
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
		}

		.el-icon {
			font-size: 24px;
			color: var(--el-color-primary);
			margin-bottom: 8px;
		}

		span {
			font-size: 14px;
			color: var(--el-text-color-regular);
		}
	}
}

/* 更新对话框样式 */
.update-content {
	padding: 10px;
	
	p {
		margin: 10px 0;
		font-size: 14px;
	}
	
	.el-progress {
		margin: 20px 0;
	}
}
</style>
